package org.littlesun.management.jface.fieldassist;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.jface.fieldassist.ContentProposal;
import org.eclipse.jface.fieldassist.IContentProposal;
import org.eclipse.jface.fieldassist.IContentProposalProvider;
import org.littlesun.management.address.AddressSuggester;
import org.littlesun.management.address.Cities;
import org.littlesun.management.address.City;

public abstract class AddressContentProposalProvider implements IContentProposalProvider {

	protected IContentProposal[] contentProposals;

	protected boolean filterProposals = false;

	protected List<City> cities;

	public AddressContentProposalProvider(List<City> cities) {
		super();
		this.cities = cities;
	}
	
	@SuppressWarnings(value={"unchecked", "rawtypes"})
	public IContentProposal[] getProposals(String contents, int position) {
		String[] proposals = new AddressSuggester(cities).getSuggestions(contents).toArray(new String[] {});
		if (filterProposals) {
			ArrayList list = new ArrayList();
			for (int i = 0; i < proposals.length; i++) {
				String proposal = proposals[i];
				if (accept(contents, proposal)) {
					list.add(new ContentProposal(proposal));
				}
			}
			return (IContentProposal[]) list.toArray(new IContentProposal[list.size()]);
		}
		if (contentProposals == null) {
			contentProposals = new IContentProposal[proposals.length];
			for (int i = 0; i < proposals.length; i++) {
				contentProposals[i] = new ContentProposal(proposals[i]);
			}
		}
		return contentProposals;
	}

	protected abstract boolean accept(String contents, String proposal);

	public void setFiltering(boolean filterProposals) {
		this.filterProposals = filterProposals;
		// Clear any cached proposals.
		contentProposals = null;
	}
	
//	public static AddressContentProposalProvider startsWith() {
//		return new AddressContentProposalProvider() {
//			protected boolean accept(String contents, String proposal){
//				if (contents != null) contents = contents.trim();
//				return StringUtils.startsWithIgnoreCase(proposal, contents);
//			}
//		};
//	}
//	
//	public static AddressContentProposalProvider contains() {
//		return new AddressContentProposalProvider() {
//			protected boolean accept(String contents, String proposal){
//				if (contents != null) contents = contents.trim();
//				boolean accept = StringUtils.containsIgnoreCase(proposal, contents);
//				return accept;
//			}
//		};
//	}
	
}
